package com.idea.cery.springboot1.task;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author:cery
 * @Version 1.0
 * @Date:2020/4/8
 */

@Component
@Configurable
@EnableScheduling
public class SystemTasks {
    /**
     * 单线程任务丢失，转为异步线程池
     * 如果任务的执行时间超过该任务的下一次执行时间，则会出现任务丢失，跳过该段时间的任务
     */
    //每20秒执行一次
    @Async
    @Scheduled(fixedRate = 1000 * 20)
    public void initSystem() {
        System.out.println("Scheduling Tasks fixedRate Examples: The time is now " + dateFormat().format(new Date()));
    }

    //表示方法执行完成后10秒
    @Scheduled(fixedDelay = 10000)
    public void initSystem1() {
        System.out.println("Scheduling Tasks fixedDelay Examples: The time is now " + dateFormat().format(new Date()));
    }

    /**
     * Cron表达式是一个字符串，字符串以5或6个空格隔开，分为6或7个域，每一个域代表一个含义，Cron有如下两种语法格式：
     * <p>
     * 1.Seconds Minutes Hours DayofMonth Month DayofWeek Year
     * 2.Seconds Minutes Hours DayofMonth Month DayofWeek
     */
    //表示每天8时30分0秒执行
    @Scheduled(cron = "0 30 8 ? * ? ")
    public void initSystem2() {
        System.out.println("Scheduling Tasks cron Examples: The time is now " + dateFormat().format(new Date()));
    }

    private SimpleDateFormat dateFormat() {
        return new SimpleDateFormat("HH:mm:ss");
    }
}
